//
//  XOShoppingCartViewController.m
//  EnjoyShoppingStreet
//
//  Created by lifayu on 2018/3/16.
//  Copyright © 2018年 lifayu. All rights reserved.
//

#import "XOShoppingCartViewController.h"
#import "EJSSettleViewController.h"

#import "XOShoppingCartShopHeaderView.h"
#import "EJSShopCartGoodsCell.h"

//#import "XOShoppingCartListRequest.h"
#import "EJSUpdateShopCartRequest.h"
#import "JSONKit.h"
#import "XOShoppingCartModel.h"
#import "XONoStockGoodsViewController.h"
#import "EJSShoppingCarSingleton.h"
#import "EJSDeleteShopCartItemRequest.h"

@interface XOShoppingCartViewController ()<UITableViewDataSource,UITableViewDelegate,XOShoppingCartShopHeaderViewDelegate,EJSShopCartGoodsCellDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *totalLabel;
@property (weak, nonatomic) IBOutlet UIButton *settleButton;
@property (weak, nonatomic) IBOutlet UIView *haveStockView;

@property (strong, nonatomic) XOShoppingCartListModel *shoppingCartListModel;
@property(nonatomic, strong) XOShoppingCartModel * shopModel;

@end

@implementation XOShoppingCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(noti_updateShoppingCarList) name:Noti_UpdateShoppingCarList object:nil];
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)setShopModel:(XOShoppingCartModel *)shopModel {
    _shopModel = shopModel;
    self.haveStockView.hidden = [_shopModel.isStock intValue] == 0;
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([EJSUserModel userModel]) {
        [self loadShoppingCartList];
    }else {
        [self showNoDataViewWithText:@"暂无购物车商品"];
    }
}

///初始化
- (void)configOwnViews{

    [self configNavigationRightItemWithImage:[UIImage imageNamed:@"delete-1"]];
    [self.settleButton setBackgroundImage:[UIImage fly_imageWithColor:AppMainColor] forState:UIControlStateNormal];
    [self.settleButton setBackgroundImage:[UIImage fly_imageWithColor:[UIColor lightGrayColor]] forState:UIControlStateDisabled];

    [self.tableView registerNib:[UINib nibWithNibName:@"EJSShopCartGoodsCell" bundle:nil] forCellReuseIdentifier:@"EJSShopCartGoodsCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"XOShoppingCartShopHeaderView" bundle:nil]forHeaderFooterViewReuseIdentifier:@"XOShoppingCartShopHeaderView"];
    self.tableView.contentInset = UIEdgeInsetsMake(-30, 0, 0, 0);

}

///删除所有购物车产品
- (void)rightBarButtonAction:(id)sender {
    [HUDHelper alertTitle:@"警告⚠️" message:@"此操作将会删除所有购物车产品? 是否继续?" cancelButtonTitle:@"按错了" confirmButtonTitle:@"确定" action:^{
        [self.shoppingCartListModel deleteAllShopGoodsWithShopID:self.shopId];
        [self updateShopCartRequest];
    }];
}

#pragma mark - loadData
- (void)loadShoppingCartList{
    if(![EJSUserTokenModel userTokenModel]){
        return;
    }
    FlyWeakSelf
    [[EJSShoppingCarSingleton sharedSingleton]updateShoppingList:^(XOShoppingCartListModel * modelList) {
        [weakSelf noti_updateShoppingCarList];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}
-(void)noti_updateShoppingCarList{
    self.shoppingCartListModel = [EJSShoppingCarSingleton sharedSingleton].shoppingList;
    if(self.shoppingCartListModel.list.count > 0){
        [self hideNoDataView];
    }else{
        [self showNoDataViewWithText:@"暂无购物车商品"];
        [self.navigationController popViewControllerAnimated:YES];
    }
    [self updateUI];
}

- (void)updateShopCartRequest{
    NSMutableArray *datas = [NSMutableArray array];
    for (EJSShoppingCartGoodsModel *goodsModel in self.shoppingCartListModel.wholeGoodsList) {
        EJSUpdateShopCartModel *model = [EJSUpdateShopCartModel new];
        model.cart_id = goodsModel.cartId;
        model.sku_id = goodsModel.spuId;
        model.num = goodsModel.num;
        [datas addObject:[model getJsonDictionary]];
    }
    
    EJSUpdateShopCartRequest *req = [EJSUpdateShopCartRequest new];
    req.data = [datas JSONString];
    [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
        [self loadShoppingCartList];
    } failHandler:^(BaseResponse *response) {
        [[HUDHelper sharedInstance] tipMessage:response.message];
    }];
}

#pragma mark - UpdateUI

- (void)updateUI{
    self.shopModel = nil;

    for (XOShoppingCartModel * model in self.shoppingCartListModel.list) {
        if ([model.shopId isEqualToString: _shopId]) {
            self.shopModel = model;
        }
    }
    self.navigationItem.title = [NSString stringWithFormat:@"%@",self.shopModel.shopName];
    if ([self.shopModel.totalAmount doubleValue] >=[self.shopModel.minBuyMomeny doubleValue]) {
         NSString *totalPriceStr = [NSString stringWithFormat:@"总金额：%.2f €",self.shopModel.totalAmount.doubleValue];
        NSMutableAttributedString *totalPriceAttrStr = [[NSMutableAttributedString alloc] initWithString:totalPriceStr];
         [totalPriceAttrStr addAttribute:NSForegroundColorAttributeName value:AppMainColor range:NSMakeRange(3, totalPriceStr.length - 3)];
        self.totalLabel.attributedText = totalPriceAttrStr;
        [self.settleButton setEnabled:YES];
    }else {
        self.totalLabel.text = [NSString stringWithFormat:@"还差%.2f€",[self.shopModel.minBuyMomeny doubleValue] - [self.shopModel.totalAmount doubleValue]];
        [self.settleButton setEnabled:NO];
    }
}


//#pragma mark - Actions

- (IBAction)settleAction:(UIButton *)sender {
    EJSSettleViewController *settleVC = [[EJSSettleViewController alloc] initWithNibName:@"EJSSettleViewController" bundle:nil];
    settleVC.settleGoods = self.shopModel.carts;
    settleVC.isNeedPopToRoot = YES;
    [self.navigationController pushViewController:settleVC animated:YES];
}

#pragma mark - 查看库存不足商品
- (IBAction)checkNullStockGoods:(id)sender {
    XONoStockGoodsViewController *vc = [[XONoStockGoodsViewController alloc] init];
    vc.shopModel = self.shopModel;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark TabelViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.shopModel.carts.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    EJSShopCartGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EJSShopCartGoodsCell" forIndexPath:indexPath];
    EJSShoppingCartGoodsModel *goodsModel = self.shopModel.carts[indexPath.row];
    [cell setShoppingGoodsCartModel:goodsModel];
    cell.delegate = self;
    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (self.shopModel.carts.count == 0){
        return [UIView new];
    }
    
    XOShoppingCartShopHeaderView *headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"XOShoppingCartShopHeaderView"];
    headerView.shoppingCartModel = self.shopModel;
    headerView.delegate = self;
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (self.shopModel.carts.count == 0){
        return 0;
    }
    return 60;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    if (section == 0) {
        return 10;
    }
    return 0.01;
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

- ( UISwipeActionsConfiguration *)tableView:(UITableView *)tableView trailingSwipeActionsConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath {
    //删除
    UIContextualAction *deleteRowAction = [UIContextualAction contextualActionWithStyle:UIContextualActionStyleDestructive title:@"delete" handler:^(UIContextualAction * _Nonnull action, __kindof UIView * _Nonnull sourceView, void (^ _Nonnull completionHandler)(BOOL)) {

        EJSDeleteShopCartItemRequest *req = [EJSDeleteShopCartItemRequest new];
        EJSShoppingCartGoodsModel *goodsModel = self.shopModel.carts[indexPath.row];
        req.cart_id = goodsModel.cartId;
        [req asyncRequestWithsuccessHandler:^(BaseResponse *response) {
            [self.shopModel.carts removeObjectAtIndex:indexPath.row];            
            [self updateShopCartRequest];

            completionHandler (YES);
        } failHandler:^(BaseResponse *response) {
            completionHandler(NO);
            [[HUDHelper sharedInstance] tipMessage:response.message];
        }];
        
    }];

    deleteRowAction.title = @"删除";
    deleteRowAction.backgroundColor = [UIColor redColor];
    UISwipeActionsConfiguration *config = [UISwipeActionsConfiguration configurationWithActions:@[deleteRowAction]];
    return config;
}


#pragma mark - XOShoppingCartShopHeaderViewDelegate
- (void)headerView:(XOShoppingCartShopHeaderView *)headerView select:(BOOL)select model:(XOShoppingCartModel *)shoppingCartModel{
    shoppingCartModel.wholeSelected = select;
    [self updateUI];
}

#pragma mark - EJSShopCartGoodsCellDelegate
- (void)shopCartGoodsCell:(EJSShopCartGoodsCell *)cell selectGoods:(EJSShoppingCartGoodsModel *)model{
    model.selectState = !model.selectState;
    [self updateUI];
}

- (void)shopCartGoodsCell:(EJSShopCartGoodsCell *)cell addGoodsNum:(EJSShoppingCartGoodsModel *)model{
    model.selectState = YES;
    NSInteger selectNum = model.num.intValue;
    model.num = @(selectNum + model.minToBuy.intValue).stringValue;
    [self updateShopCartRequest];
}

- (void)shopCartGoodsCell:(EJSShopCartGoodsCell *)cell substractGoodsNum:(EJSShoppingCartGoodsModel *)model{
    model.selectState = YES;
    NSInteger selectNum = model.num.intValue;
    if(selectNum - model.minToBuy.intValue > 0){
        model.num = @(selectNum - model.minToBuy.intValue).stringValue;
        [self updateShopCartRequest];
    }else if (selectNum - model.minToBuy.intValue <= 0){
        [self shopCartGoodsCell:cell deleteGoods:model];
    }
}

- (void)shopCartGoodsCell:(EJSShopCartGoodsCell *)cell deleteGoods:(EJSShoppingCartGoodsModel *)model{
    [HUDHelper alertTitle:@"提示" message:@"是否删除购物车中的该商品" cancelButtonTitle:@"取消" confirmButtonTitle:@"确认" action:^{
        [self.shoppingCartListModel deleteGoods:model];
        [self updateShopCartRequest];
    }];
}
@end
